package producer

import (
	"fmt"
	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"github.com/apache/rocketmq-client-go/v2/producer"
	uuid "github.com/satori/go.uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/api/constans"
	"go-zero-project/services/user/api/internal/config"
)

func InitDefaultProducer(config *config.MqConfig) (rocketmq.Producer, error) {
	list := config.TopicList
	if len(list) < 1 {
		logx.Errorf("not setting topic info, check conf...")
		return nil, excption.NewErrCode(constans.MqSkipLoadErr)
	}
	if !containsNoTransTopic(list) {
		logx.Errorf("topic all trans Topic,not init default producer ...")
		return nil, excption.NewErrCode(constans.MqSkipLoadErr)
	}
	// 地址
	namesrvs := []string{config.Namesrv}
	// 生产者组名称
	var groupName = config.GroupName
	// 设置消息轨迹
	traceCfg := &primitive.TraceConfig{
		Access:   primitive.Local,
		Resolver: primitive.NewPassthroughResolver(namesrvs),
	}
	// 高并发保证name唯一 多个producer 需要设置实例Id
	instanceId := uuid.NewV4()
	// 设置生产者
	p, err := rocketmq.NewProducer(
		producer.WithNsResolver(primitive.NewPassthroughResolver(namesrvs)),
		producer.WithGroupName(groupName),
		producer.WithRetry(config.RetryTimes),
		producer.WithTrace(traceCfg),
		producer.WithInstanceName(fmt.Sprintf("%d", instanceId)),
	)
	// 账号密码
	accessKey := config.AccessKey
	key := config.SecretKey
	if len(accessKey) > 0 && len(key) > 0 {
		credentials := primitive.Credentials{AccessKey: accessKey, SecretKey: key}
		producer.WithCredentials(credentials)
	}
	if err != nil {
		logx.Errorf("new producer error: %s", err.Error())
		return nil, err
	}
	startErr := p.Start()
	if startErr != nil {
		logx.Errorf("start producer error: %s", startErr.Error())
		return nil, startErr
	}
	logx.Infof("init defaultProducer success !")
	return p, nil
}

func containsNoTransTopic(list []config.TopicConfig) bool {
	for _, v := range list {
		if v.TopicType == 1 ||
			v.TopicType == 2 || v.TopicType == 3 {
			return true
		}
	}
	return false
}
